package com.youzikj.wx.comm.util;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.youzikj.wx.comm.menu.Menu;

/**
 * 自定义菜单工具类
 * @author Administrator
 *
 */
public class MenuUtil {
	
	private static Logger log = Logger.getLogger(MenuUtil.class);
	
	//菜单创建（post）
	public final static String menu_create_url ="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
	
	//菜单查询(get)
	public final static String menu_get_url ="https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
	
	//菜单删除(get)
	public final static String menu_delete_url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";

	/**
	 * 创建菜单
	 * @param menu 菜单实例
	 * @param accessToken  凭证
	 * @return true 成功 ，false 失败
	 */
	public static boolean createMenu(Menu menu,String accessToken){
		boolean result = false;
		String url = menu_create_url.replace("ACCESS_TOKEN", accessToken);
		//菜单对象转换成json
		String jsonMenu = JSONObject.fromObject(menu).toString();
		//请求创建菜单
		JSONObject jsonObject = CommonUtil.httpsRequest(url, "POST", jsonMenu);
		if(null != jsonObject){
			int errcode = jsonObject.getInt("errcode");
			String errorMsg = jsonObject.getString("errmsg");
			if(0 == errcode){
				result = true;
			} else {
				result = false;
				log.error("创建菜单失败，errcode:"+errcode+" errorCode: "+errorMsg);
			}
		}
		return result;
	}
	
	/**
	 * 查询菜单
	 * @param accessToken 凭证
	 * @return
	 */
	public static String getMenu(String accessToken){
		String result = null;
		String requestUrl = menu_get_url.replace("ACCESS_TOKEN", accessToken);
		//请求查询
		JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
		if(null != jsonObject){
			result = jsonObject.toString();
		}
		return result;
	}
	
	public static boolean deleteMenu(String accessToken){
		boolean result = false;
		String url = menu_delete_url.replace("ACCESS_TOKEN", accessToken);
		//请求删除菜单
		JSONObject json = CommonUtil.httpsRequest(url, "GET", null);
		if(null != json){
			int errcode = json.getInt("errcode");
			String errmsg = json.getString("errmsg");
			if(0 == errcode){
				result = true;
			} else {
				result = false;
				log.error("删除菜单失败，errcode:"+errcode+" errmsg: "+errmsg);
			}
		}
		return result;
	}
	
}
